/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Planilla_View_Add.java
 *
 * Created on 2/05/2012, 11:44:10 PM
 */
package v;

import c.PlanillasController;
import core.constructor.constructor;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import tools.Util;

/**
 *
 * @author Usuario
 */
//validar que un medico no tenga asignado planillas el mismo dia en el mismo 
//horario
//
public class Planilla_View_Add extends javax.swing.JPanel {

    private constructor c;
    private String id_medico;
    private String campoPK;
    private PlanillasController controler = new PlanillasController();
    private String mod = "";
    private String llave = "";

//    private SimpleDateFormat formatoDeHoraMil = new SimpleDateFormat("kk:mm");
//    private SimpleDateFormat formatoDeHora = new SimpleDateFormat("hh:mm a");
//    private SimpleDateFormat formatoDeFecha = new SimpleDateFormat("yy-MM-dd");
    /**
     * Creates new form Planilla_View_Add
     */
    public Planilla_View_Add(Object... e) {
        initComponents();
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 8);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        jInicio.setValue(cal.getTime());
        jFin.setValue(cal.getTime());
        config(e);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        Panel = new javax.swing.JPanel();
        jFin = new javax.swing.JSpinner(new SpinnerDateModel(
            new Date(), null, null, Calendar.HOUR_OF_DAY));
    jxFecha = new org.jdesktop.swingx.JXDatePicker();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    bAgregar = new javax.swing.JButton();
    bCancelar = new javax.swing.JButton();
    jXTitledSeparator1 = new org.jdesktop.swingx.JXTitledSeparator();
    jLabel4 = new javax.swing.JLabel();
    cNombres = new javax.swing.JTextField();
    jFind = new javax.swing.JButton();
    jLabel5 = new javax.swing.JLabel();
    cApellidos = new javax.swing.JTextField();
    jXTitledSeparator2 = new org.jdesktop.swingx.JXTitledSeparator();
    jLabel6 = new javax.swing.JLabel();
    jInicio = new javax.swing.JSpinner(new SpinnerDateModel(
        new Date(), null, null, Calendar.HOUR_OF_DAY));

Panel.addInputMethodListener(new java.awt.event.InputMethodListener() {
    public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
    }
    public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
        PanelInputMethodTextChanged(evt);
    }
    });
    Panel.setLayout(new java.awt.GridBagLayout());
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 19;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.gridheight = 2;
    gridBagConstraints.ipadx = 43;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(7, 7, 0, 10);
    Panel.add(jFin, gridBagConstraints);

    jxFecha.setFormats("dd-MM-yyyy");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.gridheight = 3;
    gridBagConstraints.ipadx = 20;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(6, 17, 0, 0);
    Panel.add(jxFecha, gridBagConstraints);

    jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel2.setText("Hora Inicio");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 4;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.gridheight = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0);
    Panel.add(jLabel2, gridBagConstraints);

    jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel3.setText("Hora Final");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 12;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.gridwidth = 6;
    gridBagConstraints.gridheight = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0);
    Panel.add(jLabel3, gridBagConstraints);

    bAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/guardar32.png"))); // NOI18N
    bAgregar.setText("Guardar");
    bAgregar.setEnabled(false);
    bAgregar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bAgregarActionPerformed(evt);
        }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 10;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(18, 87, 11, 0);
    Panel.add(bAgregar, gridBagConstraints);

    bCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/cancelar32.png"))); // NOI18N
    bCancelar.setText("Cancelar");
    bCancelar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bCancelarActionPerformed(evt);
        }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 8;
    gridBagConstraints.gridy = 10;
    gridBagConstraints.gridwidth = 5;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(18, 10, 11, 0);
    Panel.add(bCancelar, gridBagConstraints);

    jXTitledSeparator1.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
    jXTitledSeparator1.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
    jXTitledSeparator1.setTitle("Datos Médico");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = 20;
    gridBagConstraints.ipadx = 371;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 10);
    Panel.add(jXTitledSeparator1, gridBagConstraints);

    jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel4.setText("Nombres");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(9, 5, 0, 0);
    Panel.add(jLabel4, gridBagConstraints);

    cNombres.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    cNombres.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            cNombresActionPerformed(evt);
        }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridwidth = 16;
    gridBagConstraints.gridheight = 2;
    gridBagConstraints.ipadx = 317;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(6, 18, 0, 0);
    Panel.add(cNombres, gridBagConstraints);

    jFind.setIcon(new javax.swing.ImageIcon(getClass().getResource("/core/img/busqueda32.png"))); // NOI18N
    jFind.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jFindActionPerformed(evt);
        }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 19;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.gridheight = 3;
    gridBagConstraints.ipadx = 6;
    gridBagConstraints.ipady = -16;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(5, 8, 0, 10);
    Panel.add(jFind, gridBagConstraints);

    jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel5.setText("Fecha");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(7, 5, 0, 0);
    Panel.add(jLabel5, gridBagConstraints);

    cApellidos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 3;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.gridwidth = 17;
    gridBagConstraints.gridheight = 2;
    gridBagConstraints.ipadx = 396;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(12, 18, 0, 10);
    Panel.add(cApellidos, gridBagConstraints);

    jXTitledSeparator2.setFont(new java.awt.Font("Tahoma", 1, 15)); // NOI18N
    jXTitledSeparator2.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
    jXTitledSeparator2.setTitle("Información planilla");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 6;
    gridBagConstraints.gridwidth = 20;
    gridBagConstraints.ipadx = 320;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(18, 5, 0, 10);
    Panel.add(jXTitledSeparator2, gridBagConstraints);

    jLabel6.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel6.setText("Apellidos");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 4;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(15, 5, 0, 0);
    Panel.add(jLabel6, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 5;
    gridBagConstraints.gridy = 7;
    gridBagConstraints.gridwidth = 4;
    gridBagConstraints.gridheight = 2;
    gridBagConstraints.ipadx = 43;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
    gridBagConstraints.insets = new java.awt.Insets(7, 10, 0, 0);
    Panel.add(jInicio, gridBagConstraints);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(Panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(Panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    }// </editor-fold>//GEN-END:initComponents

    private void bAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bAgregarActionPerformed
        // TODO add your handling code here:
        prepararTransaccion();
    }//GEN-LAST:event_bAgregarActionPerformed

    private void bCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelarActionPerformed
        if (c != null) {
            c.ventPrincipal();
        } else {
            Logger.getLogger(Acudiente_View_Add.class.getName()).log(Level.WARNING, "La Clase Constructor no ha sido instanciada");
        }

    }//GEN-LAST:event_bCancelarActionPerformed

    private void jFindActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFindActionPerformed
        SeleccionadorIU select = new SeleccionadorIU("SELECT id_medico,identificacion,nombres, apellidos, descripcion FROM medico natural join especialidad", "CODIGO,CEDULA,NOMBRES,APELLIDOS,ESPECIALIDAD", c, this.getClass().getName(), "cargar");
//        select.setBounds(0, 0, 453, 189);
        select.setVisible(true);
        Map<String, String> datos = select.getDatosSelect();
        if (!datos.isEmpty()) {
            cargar(select.getDatosSelect());
            bAgregar.setEnabled(true);
        }
    }
        //c.ventanaEmergente("SELECT id_acudiente,id_identificacion,nombres FROM acudiente", "CODIGO,CEDULA,NOMBRES", c , this.getClass().getName() , "cargar");          SeleccionadorIU select = new SeleccionadorIU("SELECT id_acudiente,id_identificacion,nombres FROM acudiente", "CODIGO,CEDULA,NOMBRES", c, this.getClass().getName(), "cargar");         select.setVisible(true);         select.setBounds(0, 0, 453, 189);         cargar(select.getDatosSelect());      }//GEN-LAST:event_jFindActionPerformed

    private void cNombresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cNombresActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cNombresActionPerformed

    private void PanelInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_PanelInputMethodTextChanged
    }//GEN-LAST:event_PanelInputMethodTextChanged

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel Panel;
    private javax.swing.JButton bAgregar;
    private javax.swing.JButton bCancelar;
    private javax.swing.JTextField cApellidos;
    private javax.swing.JTextField cNombres;
    private javax.swing.JSpinner jFin;
    private javax.swing.JButton jFind;
    private javax.swing.JSpinner jInicio;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private org.jdesktop.swingx.JXTitledSeparator jXTitledSeparator1;
    private org.jdesktop.swingx.JXTitledSeparator jXTitledSeparator2;
    private org.jdesktop.swingx.JXDatePicker jxFecha;
    // End of variables declaration//GEN-END:variables

    private void config(Object... e) {

        JSpinner.DateEditor de = new JSpinner.DateEditor(jInicio, "hh:mm a");
        jInicio.setEditor(de);

        JSpinner.DateEditor de2 = new JSpinner.DateEditor(jFin, "hh:mm a");
        jFin.setEditor(de2);

        jxFecha.setDate(new Date());
        if (e.length > 0) {
            try {
                c = (constructor) e[0];

                //Configura la Interfaz para el Modo en el que fue invocado
                configModo((String) e[1], (String) e[2]);
            } catch (Exception exc) {
                System.err.println("(config())Error de Asignacion , compruebe el numero de Parametros que envia .. " + exc.getMessage());
                exc.printStackTrace();
            }
        }
        // Indicar a las 'migas de pan' donde estamos.
        c.setNavegar("Planilla_View_Grid");
        c.setLabelModulo("Planillas");
        c.setLabelAccion("Agendar Médico");
    }

    private void cargar(Map<String, String> datosSelect) {
        cNombres.setText(datosSelect.get("NOMBRES"));
        cApellidos.setText(datosSelect.get("APELLIDOS"));
        id_medico = datosSelect.get("CODIGO");
    }

    private void prepararTransaccion() {

        if (!esFechaValida()) {
            c.informarUsuario("error[¡Fecha seleccionada incorrecta]  No se pueden agendar fechas pasadas");
            return;
        } else if (!horasCorrectas()) {
            c.informarUsuario("error[¡Horas no coinciden]  La hora final debe ser posterior a la inicial.");
            return;
        }

        String tablaBD = "planilla_horario";

        StringBuilder sqlAndRestricciones = new StringBuilder();
        StringBuilder camposBD = new StringBuilder();
        StringBuilder valoresBD = new StringBuilder();

//        por lo pronto estare usando este metodo alterno
        if ("".equals(llave)) {
            insertAlterno();
        } else {
            updatePlanilla();
        }

        //aca esta el problema
//        sqlAndRestricciones.append("Id Medico@id_medico='" + id_medico.toLowerCase() + "'[-(0,0)]&");
//        sqlAndRestricciones.append("Fecha@fecha_agendada='" + jxFecha.getDate().toString() + "'[-(0,0)]&");
//        sqlAndRestricciones.append("Hora inicio@hora_inicio='" + "8:00" + "'[-(0,0)]&");
//        sqlAndRestricciones.append("Hora final@hora_fin='" + "9:00" + "'[-(0,0)]");
//        
//        String mensajeUsuario  = controler.prepararTransaccion(tablaBD, sqlAndRestricciones, mod, "La planilla", campoPK);
//
//        c.informarUsuario(mensajeUsuario);
    }

    private void configModo(String m, String key) {
        mod = m;

        String SQL_BUSCAR = String.format(
                "SELECT id_medico, id_planilla_horario, nombres, apellidos, "
                + "fecha_agendada, "
                + "hora_inicio, hora_fin FROM planilla_horario natural join "
                + "medico where id_planilla_horario = '%s' ", key);

        if (!m.equals("")) {

            if (!m.equals("INSERT")) {
                campoPK = "id_horario = " + key;
            }

            if (m.equals("SELECT")) {
                System.out.println("mod = " + m);
                System.out.println("key = " + key);
                estadoComponentes(false);
                c.setLabelAccion("Consulta Planilla");
                setPlanilla(controler.buscar(SQL_BUSCAR));
            } else if (m.equals("UPDATE")) {
                llave = key;
                System.out.println("mod = " + m);
                System.out.println("key = " + key);

                estadoComponentes(true);

                c.setLabelAccion("Modificar Planilla");
                setPlanilla(controler.buscar(SQL_BUSCAR));
                bAgregar.setText("Actualizar");
                bAgregar.setEnabled(true);
                jInicio.setEnabled(false);
                jFin.setEnabled(false);
                //Cambiar icono here...

                //Tomar cuando arranque la pantalla los campos UNQ
            }
        }
    }

    private void estadoComponentes(boolean b) {
        jFind.setEnabled(b);
        cNombres.setEditable(b);
        cApellidos.setEditable(b);
        jxFecha.setEditable(b);
        jInicio.setEnabled(b);
        jFin.setEnabled(b);
    }

    private void setPlanilla(Object[][] buscar) {
//        "SELECT id_medico, id_planilla_horario, nombres, apellidos, fecha_agendada, "
//                + "hora_inicio, hora_fin FROM planilla_horario natural join medico where id_planilla_horario = '%s' ", key);
        cNombres.setText(buscar[0][2].toString());
        cApellidos.setText(buscar[0][3].toString());
        id_medico = buscar[0][0].toString();
        SimpleDateFormat formatoDeHoraMil = new SimpleDateFormat("kk:mm");
        SimpleDateFormat formatoDeFecha = new SimpleDateFormat("yy-MM-dd");

        try {
            jxFecha.setDate(formatoDeFecha.parse(buscar[0][4].toString()));
            jInicio.setValue(formatoDeHoraMil.parse(buscar[0][5].toString()));
            jFin.setValue(formatoDeHoraMil.parse(buscar[0][6].toString()));
        } catch (ParseException ex) {
            System.out.println(ex);
        }
    }

    private boolean horasCorrectas() {

        if (getHoraValida((Date) jFin.getValue()).
                equals(getHoraValida((Date) jInicio.getValue()))) {
            return false;

        }
        if (getHoraValida((Date) jFin.getValue())
                .before(getHoraValida((Date) jInicio.getValue()))) {
            return false;
        }
        return true;
    }

    private Date getHoraValida(Date date) {
        SimpleDateFormat formatoDeFecha = new SimpleDateFormat("hh:mm a");
        Date result = null;
        try {
            result = formatoDeFecha.parse(formatoDeFecha.format(date));
        } catch (ParseException ex) {
            System.out.println(ex);
        }
        return result;
    }

    private boolean esFechaValida() {
        Date actual = new Date();
        Date selected = jxFecha.getDate();
        if ((actual.getYear() == selected.getYear()
                && actual.getMonth() == selected.getMonth()
                && actual.getDate() == selected.getDate()) || selected.after(actual)) {
            return true;
        }
        return false;
    }

    private void insertAlterno() {
        String sentencia = new String("INSERT INTO planilla_horario"
                + "(id_medico,fecha_agendada,hora_inicio,hora_fin) "
                + "VALUES('%s','%s','%s','%s')");

        SimpleDateFormat formatoDeFecha = new SimpleDateFormat("hh:mm a");

        sentencia = String.format(sentencia, id_medico.toLowerCase(),
                jxFecha.getDate().toString(),
                formatoDeFecha.format(jInicio.getValue()),
                formatoDeFecha.format(jFin.getValue()));

        System.out.println(sentencia);
        if (controler.add(sentencia)) {

            String ultimo = "select * from planilla_horario order by id_planilla_horario desc limit 1";
            Object[][] resul = controler.buscar(ultimo);
            if (llenarCitas((String) resul[0][0])) {
                c.informarUsuario("ok[Generación de planilla]  Se guardo "
                        + "correctamente la información");
                Util.limpiarCamposForm(this);
                //mostrar mensaje de exito a usuario
                
                bAgregar.setEnabled(false);
            } else {
                c.informarUsuario("error[Error al insertar]  No se pudo guardar "
                        + "la información");
            }
        }
    }

    private boolean llenarCitas(String idPlanilla) {
        int fraccion = 15;
        SimpleDateFormat formatoDeHora = new SimpleDateFormat("hh:mm a");
        Date inicio = getHoraValida((Date) jInicio.getValue());
        Date fin = getHoraValida((Date) jFin.getValue());
        Integer total = (int) (fin.getTime() - inicio.getTime()) / (fraccion * 60000);
        System.out.println("Total: " + total);
        String insertCita = "INSERT INTO cita("
                + "id_planilla_horario,estado, hora) "
                + "VALUES ('" + idPlanilla + "', '0', '%s');";
        Date horaCita = new Date();
        horaCita.setTime(inicio.getTime());
        String cita;
        for (int i = 0; i < total; i++) {
            cita = String.format(insertCita, formatoDeHora.format(horaCita));
            if (!controler.add(cita)) {
                return false;
            }
            horaCita.setTime(horaCita.getTime() + (fraccion * 60000));
        }
        return true;
    }

    private void updatePlanilla() {
        String update = "UPDATE planilla_horario "
                + "SET id_medico = '%s', fecha_agendada = '%s'"
                + " WHERE id_planilla_horario= '%s';";
        update = String.format(update, id_medico,
                jxFecha.getDate().toString(),
                llave);
        System.out.println(update);
        if (controler.add(update)) {
            System.out.println("Exito al insertar en la base de datos");
            c.informarUsuario("ok[Actualización de planilla]  Se guardo "
                    + "correctamente la información");
        } else {
            c.informarUsuario("error[Error al insertar]  No se pudo actualizar "
                    + "la información");
        }
    }
}